package com.ipay.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import net.sf.json.JSONObject;

/***
 * @author V型知识库  www.vxzsk.com
 *
 */
public class JsapiTicketUtil {

    /***
     * 模拟get请求
     * @param url
     * @param charset
     * @param timeout
     * @return
     */
    public static String sendGet(String url, String charset, int timeout) {
        StringBuffer result=new StringBuffer();
        try {
            URL u = new URL(url);
            try {
                URLConnection conn = u.openConnection();
                conn.connect();
                conn.setConnectTimeout(timeout);
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
                String line = "";
                while ((line = in.readLine()) != null) {
                    result.append(line);
                }
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    /***
     * 获取acess_token
     * 来源www.vxzsk.com
     * @return
     */
    public static String getAccessToken() {
        String appid = "wxf7fca97aabff09c9";
        String secret = "cafb0ad5a520a2f1c8255e2dd9c9f286";

        String result = HttpUtils.requestHttp(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                        + appid + "&secret=" + secret,
                "get", "");
        JSONObject jsonObject = JSONObject.fromObject(result);
        System.out.println("access_token" + result);
        String token = jsonObject.getString("access_token");
        return token;
    }

    /***
     * 获取jsapiTicket
     * 来源 www.vxzsk.com
     * @return
     */
    public static String getJSApiTicket() {
        //获取token
        String acess_token = JsapiTicketUtil.getAccessToken();
        String backData = HttpUtils.requestHttp(
                "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="
                        + acess_token + "&type=jsapi",
                "get", "");

        String ticket = (String) JSONObject.fromObject(backData).get("ticket");
        System.out.println("调用微信jsapi的凭证票为：" + ticket);
        return ticket;

    }

    public static void main(String[] args) {
        String jsapiTicket = JsapiTicketUtil.getJSApiTicket();
        System.out.println("调用微信jsapi的凭证票为：" + jsapiTicket);
    }
}
